package org.example.pinda.util;

import org.springframework.context.ApplicationContext;
import org.springframework.util.Assert;

import java.util.Map;

/**
 * Spring 工具类
 *
 * @author ryan fawcett
 */
public class SpringUtils {

    private static ApplicationContext applicationContext;

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    public static void setApplicationContext(ApplicationContext ctx) {
        Assert.notNull(ctx, "SpringUtils injection ApplicationContext is null");
        SpringUtils.applicationContext = ctx;
    }

    /**
     * 根据Bean名称获取Bean对象
     *
     * @param name Bean名称
     * @return Bean对象
     */
    public static Object getBean(String name) {
        Assert.hasText(name, "Bean name is null or empty");
        return applicationContext.getBean(name);
    }

    /**
     * 通过Bean名称及其类型获取Bean对象
     *
     * @param name   Bean名称
     * @param tClass 类型
     * @param <T>    类型
     * @return Bean对象
     */
    public static <T> T getBean(String name, Class<T> tClass) {
        Assert.hasText(name, "Bean name is null or empty");
        Assert.notNull(tClass, "Bean type is null");
        return applicationContext.getBean(name, tClass);
    }

    /**
     * 通过Bean类型获取Bean对象
     *
     * @param tClass 类型
     * @param <T>    类型
     * @return Bean对象
     */
    public static <T> T getBean(Class<T> tClass) {
        Assert.notNull(tClass, "Bean type is null");
        return applicationContext.getBean(tClass);
    }

    /**
     * 通过类型获取Bean集合
     *
     * @param tClass 类型
     * @param <T>    类型
     * @return Bean Map集合
     */
    public static <T> Map<String, T> getBeansOfType(Class<T> tClass) {
        Assert.notNull(tClass, "Bean type is null");
        return applicationContext.getBeansOfType(tClass);
    }

}
